// pages/Personal_matches/match/match.js
const app = getApp()
const socketUrl = app.globalData.socketHost
var socketStatus = 'closed'
import {
  completeMatch,
  getMatchInfo,
  getScoring,
  addPlayer,
  getLookers,
  getCourseInfo,
  updateMatch,
  addLookers,
  addScore,
  addStatistics,
  getPlayList,
  deleteScore,
  getTee,
  addTee,
  getKickData,
  addKick,
  getPlayerQR,
  getmatchpic,
  viewed,
} from '../../../http/game'
import {
  arrayChunk
} from '../../../utils/utils'
import {
  uploadImage
} from '../../../utils/upload'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    staticUrl: app.globalData.staticUrl,
    scorecard: {},
    player_index: 0,
    hole_index: 1,
    displaytype:1, //显示topar 还是总杆 1位总杆 2为topar,
    groupInfo:{},
    thurmbs:[],
    baseimgaeUrl:"",
    page:1,
    v_id:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const {
      match_id
    } = options
    const my_id = app.globalData.userInfo.player_id;
    const my_name = app.globalData.userInfo.nickName;
    this.setData({
      match_id,
      my_id,
      my_name
    });
    this.getMatchInfo() //获取球局详情
    this.getScoring() //获取球局总数据
    this.getmatchpic();//获取相册
    this.viewed(); //流量统计
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.popupqrcode = this.selectComponent("#popupqrcode");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.viewed(true);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
        this.getmatchpic();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
  // if (e.from === 'button') {
    console.log(e);
    if (e.target && e.target.dataset.type=='share') {
      this._successPlayer()
     // this.websocketGame()
      //socketType = 'invite'
      const { my_id, match_id, my_name, match_billno,matchInfo } = this.data
        console.log(matchInfo);
      return {
          title:  this.data.isMyMatch? `${my_name} 邀请您加入记分卡`:`${my_name} 的记分卡`,
          imageUrl:'/images/thurmb.png',
          path: `/pages/Personal_matches/friend/friend?id=${my_id}&c=${matchInfo.course_id}&match_billno=${match_billno}&time=${matchInfo.pm_start_date}`
         
      }

    }
    else if(e.target && e.target.id=='tofriends'){
      const { my_id, match_id, my_name, match_billno } = this.data

      return {
          title: this.data.isMyMatch? `${my_name} 邀请您加入记分卡`:`${my_name} 的记分卡`,
          imageUrl:'/images/thurmb.png',
          path: `/pages/Personal_matches/match/match?match_id=${match_id}`
      }
    }
    else{
      const { my_id, match_id, my_name, match_billno } = this.data

      return {
          title: `${my_name} 邀请您观看记分卡`,
          imageUrl:'/images/thurmb.png',
          path: `/pages/Personal_matches/match/match?match_id=${match_id}`
      }
    }
 
 
  },

  onShareTimeline:function() {
    const { my_id, match_id, my_name, match_billno } = this.data
    return {
      title: `${my_name} 邀请您观看记分卡`,
      imageUrl:'/images/iconlogo.png',
      query: `match_id=${match_id}`
  }
  },

  viewed:function(ishide) {
    var  userInfo = app.globalData.userInfo;
    //console.log(user_id);
    let{match_id} = this.data;
    var user_id = userInfo.userID;
    //var player_id = userInfo.player_id || '';
    
    let{v_id} = this.data;
    if(ishide){
        if(v_id){
            
        }
        else{
            return;
        }
    }
    else{
        v_id = "";
    }

    var that = this;
    viewed({person_mt_id:match_id,user_id,v_id}).then(res => {
        console.log(res);
        if(res.errorcode.code='ok'){
        that.setData({
          v_id:res.data||"",
        })
        console.log(that.data.v_id);
      }
    })
},

  getmatchpic:function(isrefresh) {
    let{match_id,thurmbs,page} = this.data;
    var that = this;
    getmatchpic({match_id,page}).then(res=>{

          if(res.errorcode.code == 'ok'){
            console.log(res.data);
            console.log(page);
            if(res.data && res.data.length>0){
              
              thurmbs =res.data;
              page = page+1;
              that.setData({thurmbs,page,isbottom:false});
              if(isrefresh){  //刷新
                that.selectComponent('#thumbscontent').refreshImage(thurmbs);
            }
            }
            if(res.data && res.data.length<=0 && page > 1){
               that.setData({isbottom:true,})
            }
          
          }
      }
      );
  },

  // 获取球局详情
  async getMatchInfo() {

    let {
      match_id,
      my_id,
      isMyMatch,
    } = this.data
   
    const {
      data
    } = await getMatchInfo({
      match_id,pl_id:my_id
    })
    console.log(data);
    if(data <0 ){ //球局禁用 返回
        wx.navigateBack({
          delta: -1,
        })
        return;
    }
    var player_info = data.playerlists;
    // 是否是本人球局
    const players = player_info.map(item => {
      return item.pl_id
    })
    isMyMatch = players.includes(my_id);
    console.log(data);
    this.setData({
      matchInfo: data,
      match_billno:data.match_billno,
      isMyMatch: isMyMatch,
      player_info,
      isShowFoot: isMyMatch && data.code != 3
    });
    console.log(player_info);
  },

  // 获取球局得分
  async getScoring() {
    const {
      match_id,
      my_id,

    } = this.data
    await getScoring({
      match_id
    }).then(res => {
      const {
        scorecards,
        holepars
      } = res.data
      console.log(scorecards);
      console.log(holepars);


      this.setData({
        scorecard: scorecards,
        holepars,

      });


    })
  },

  switchchange:function() {
      let{displaytype} = this.data;
      if(displaytype == 1){
        displaytype = 2;
      }
      else  if(displaytype == 2){
        displaytype = 1;
      }
      this.setData({displaytype})
      console.log(displaytype);
  },

  /** 弹框 */
  // 显示记分板
  showCoachPopup(e) {
    console.log(this.data.isMyMatch);
    if (!this.data.isMyMatch) {
      return
    }
    console.log(this.data.isMyMatch);
    const {
      hole_index,
      player_index,
      score,
      ho_par,
      type
    } = e.currentTarget.dataset
    let {
      holepars
    } = this.data;
    var current_par = "";
    if (type == 1) {
      current_par = holepars.outInfo[hole_index - 1].holePar;
    }
    if (type == 2) {
      current_par = holepars.inInfo[hole_index - 10].holePar;
    }

    const current_score = score
    console.log(e.currentTarget.dataset);
    this.setData({
      current_par,
      current_score,
      hole_index,
      player_index
    })
    this.selectComponent("#popup-coach").showPopup();
  },

  _clearScore() {
    this.handleShowScore(null)
},

showPopup() {
  this.popupqrcode.showPopup();
},

openQrcode: async function () {

  if(!this.data.isMyMatch){
        wx.showToast({
          title: '非本计分卡人员',
          icon:'none',
        })
        return;
  }

  let {  match_id,groupInfo,matchInfo} = this.data;

  groupInfo.mt_name= matchInfo.pm_cn_name;
  groupInfo.round_name = matchInfo.cr_cn_name;
  groupInfo.group_name = matchInfo.pm_cr_hole;
  groupInfo.rd_time = matchInfo.pm_start_date;
  const res = await getPlayerQR({type:2, match_id,})
  //console.log(res);
  this.setData({
      QrcodeUrl: res,
      groupInfo,
  });
  //this.websocketGame()
  this.showPopup();
},


  //计分器取消事件
  _errorCoach() {
    this.selectComponent("#popup-tee").hidePopup();
  },

  //取消事件
  _error() {
    this.selectComponent("#popup").hidePopup();
    this.selectComponent("#popup-coach").showPopup();
    
  },

  _errorqr(){
    this.selectComponent("#popupqrcode").hidePopup();
  },

  //计分器确认事件
  _successCoach(e) {
    const score = e.detail
    this.handleShowScore(score)

  },

  _openMore() {
    this.selectComponent("#popup-coach").hidePopup();
    this.selectComponent("#popup").showPopup();
  },

  //添加/修改 删除成绩
  async handleShowScore(score) {
    let {
      scorecard,
      playerScoresDisplay,
      hole_index,
      player_index,
      player_info,
      holepars,
      match_id,
      end_hole,
      hole_par,
      current_par,
      current_score
    } = this.data

    const paramsObj = {
      match_id: match_id,
      score,
      hole: hole_index,
      player_id: player_info[player_index].pl_id,
      ho_par: current_par
    }
    score === null && delete paramsObj.score

    var topar = Number(score - current_par) || 0;


    //当前球洞是否已存在分数
    if (hole_index > 9) {
      scorecard[player_index].inScore[hole_index - 10].holeScore = score=== null?'':score;
      scorecard[player_index].inScore[hole_index - 10].holetopar = score===null? "": topar ;
    } else {
      scorecard[player_index].outScore[hole_index - 1].holeScore = score=== null?'':score;
      scorecard[player_index].outScore[hole_index - 1].holetopar = score=== null?   "":topar;
    }

    const params = Object.assign(paramsObj, this.pageData)
    //console.log(params); return;
    if (score) {
      await addScore(params) // 录入分数
      if (this.data.isStatsMore) {
        this._openMore()
      }
    } else {
      await deleteScore(params) // 删除分数
    }
    this.setData({
      scorecard
    });
    console.log(scorecard);
    // 计算每人总杆 topar 
    this.computedScore()
    //this.computedTopar()
    //this.computedHalf()

    if (player_index === player_info.length - 1) {
      if (hole_index >= 18) {
        hole_index = 1;
        //this.selectComponent("#popup-coach").hidePopup()
      } else {
        hole_index += 1
        player_index = 0
      }
    } else {
      player_index += 1
    }
    if (hole_index > 9) {
      current_par = holepars.inInfo[hole_index - 10].holePar
      current_score = scorecard[player_index].inScore[hole_index - 10].holeScore;
    } else {
      current_par = holepars.outInfo[hole_index - 1].holePar
      current_score = scorecard[player_index].outScore[hole_index - 1].holeScore;
    }

    //current_score = playerScores[player_info[player_index].player_id].filter(item => item.hole_id === holes[hole_index])[0].score
    this.setData({
      current_score,
      current_par,
      player_index,
      hole_index
    })

    setTimeout(() => {
      this.getMatchInfo()
    }, 0)
  },

  computedScore() {
    let {
      scorecard,
      player_index,
      hole_index
    } = this.data;
    if (hole_index > 9) {
      var inTotal = 0;
      var intopar = 0;
      scorecard[player_index].inScore.forEach(item => {
        inTotal += Number(item.holeScore);
        intopar += Number(item.holetopar);

      })
      scorecard[player_index].inScoretotal = inTotal;
      scorecard[player_index].inScoretopar = intopar;
      scorecard[player_index].playerscore = Number(inTotal) + Number(scorecard[player_index].outScoretotal);
      scorecard[player_index].playertopar = Number(intopar) + Number(scorecard[player_index].outScoretopar);

    } else {
      var outTotal = 0;
      var outtopar = 0;
      scorecard[player_index].outScore.forEach(item => {
        outTotal += Number(item.holeScore);
        outtopar += Number(item.holetopar);

      })
      scorecard[player_index].outScoretotal = outTotal;
      scorecard[player_index].outScoretopar = outtopar;
      scorecard[player_index].playerscore = Number(outTotal) + Number(scorecard[player_index].inScoretotal);
      scorecard[player_index].playertopar = Number(outtopar) + Number(scorecard[player_index].inScoretopar);

    }
    this.setData({
      scorecard
    })
  },
  // 计算标准杆差
  computedTopar() {
    const topars = []
    const scoreList = JSON.parse(JSON.stringify(this.data.playerScoresDisplay))
    scoreList.forEach((score, index) => {
      let sum = 0
      score.forEach(item => {
        sum += item.topar || 0
      })
      const total = sum > 0 ? '+' + sum : sum
      topars[index] = {
        total,
        isComplete: score.every(s => s.score !== null)
      }
    })
    this.setData({
      totalTopar: topars
    })
  },

  //技术统计确认事件
  async _success(e) {
    const {
      match_id,
      holes,
      hole_index,
      player_index,
      player_info,
      current_score
    } = this.data
    const params = {
      match_id,
      player_id: player_info[player_index].pl_id,
      hole: hole_index,
      score: current_score,
      ...e.detail
    }
    await addStatistics(params)
    this.selectComponent("#popup").hidePopup();
  },


  async completeMatch() {
    const { isMyMatch, scorecard } = this.data
        if (!isMyMatch) { return }
        // 是否全部完成分数
        const isFullScoreout = Object.values(scorecard).some(list => {
            return list.outScore.some(item => { return !item.holeScore })
        })
        const isFullScorein = Object.values(scorecard).some(list => {
          return list.inScore.some(item => { return !item.holeScore })
      })
        if (isFullScoreout || isFullScorein) {
            wx.showModal({
                title: '提示',
                content: '还未录入完分数，是否结束球局？',
                confirmText: '结束',
                success: res => {
                    if (res.confirm) {
                        this.completeMatchFun()
                    }
                }
            })
        } else {
            this.completeMatchFun()
        }
    },
    completeMatchFun() {
        const { match_id } = this.data
        completeMatch({ match_id }).then(res => {
                this.getMatchInfo()
        })
    },

    // 显示添加球员
    showPlayersPopup(e) {
      if(this.data.isMyMatch){
      this.selectComponent("#popup-player").showPopup();
      }else{
        wx.showToast({
          title: '非本记分卡人员',
          icon:'none'
        })
      }
  },
   //确认事件
   _successPlayer() {
    this.selectComponent("#popup-player").hidePopup();
},


_addPlayer:function(e) {
    console.log(e);
    this._successPlayer();
    const data = e.detail;
    let {player_info} = this.data;
    var player = player_info.filter(item=>{return item.pl_id == data.pl_id});
    if(player && player.length>0){
       wx.showToast({
         title: '球员已在球局',
         icon:'error',
       })
       return ;
    }
    //return;
    let{match_billno,my_id,match_id} =this.data;
    addPlayer({
      match_billno: match_billno,
      player_id: my_id.toString(),
      in_player_ids:data.pl_id

  }).then(() => {
      this.getMatchInfo();
      this.getScoring()
      this.sendMessage({  type: 'join', code: 2,match_id:match_id, match_billno: match_billno,players_info:data});
  })
},



//处理消息的方法
websocketGame() {
  this.closeSocket();
  this.openSocket();

},
/**** socket *****/
openSocket() {
  let{match_billno} = this.data;
  const {nickName , player_id, avatarUrl} =app.globalData.userInfo
        const players_info = {
            player_id: player_id,
            headimg: avatarUrl,
            player_name: nickName
        }
        const params = {
            
            players_info: players_info, //我的信息
            match_billno:match_billno,
        }
        var that = this;
        var timer = setInterval(function() {
            app.websocketrevice(params,function(res) {
                    if(res.data){
                        that.handleSocket(res.data.data);
                    }
            },function() {

            })
        },5000);
            this.setData({timer});
},
//关闭信道
closeSocket() {
  if(this.data.timer){
    clearInterval(this.data.timer);
  }
},
//发送消息函数
sendMessage(params) {
  if (socketStatus === 'connected') {
    app.websocketsend(params,function(res) {
       
    },function() {

    })
}
},

// // 处理socket 
handleSocket(response) {
  const { my_id, match_billno, match_id ,player_info} = this.data
  if (response.type=='join' && response.status === 'connected' && response.match_id === match_id) {
      console.log(response)
      if(response.players_info){
       
       // 是否是本人球局
      const players = player_info.map(item => {
      return item.pl_id
      })
        isInmatch = players.includes(response.players_info.player_id);
        if(isMyMatch) //已经在组里面了
        {
          this.sendMessage({ type: 'join', code: 4,match_id:match_id, match_billno: match_billno,players_info:response.players_info }); //发送已经存在的消息给对方
          return ;
        }
      }
      addPlayer({
          match_billno: match_billno,
          player_id: my_id.toString(),
          in_player_ids:response.players_info.player_id

      }).then(() => {
          this.getScoring()
          this.sendMessage({  type: 'join', code: 2,match_id:match_id, match_billno: match_billno,players_info:response.players_info});
      })
   }
},

createThurmb:function() {
    let{match_id,thurmbs} = this.data;
    var that = this;
    uploadImage(match_id,2,function(res) {
      console.log(res);
      console.log(thurmbs);
      that.setData({page:1});
      that.getmatchpic(true);
    });
    
  }

})